﻿using System.Threading.Tasks;
using H2.NET.Common;
using H2.NET.DBUtility;
using H2.NET.Web.Management.Config.Service;
using H2.NET.Web.Pages.SMD.Helper;
using H2.NET.Web.Workflow.DwzCode;
using System;
using System.Data;
using H2.NET.Data.Common;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using H2.NET.Web.Workflow.Helper;

namespace H2.NET.Web.Pages.SMD
{
    public partial class SelectChange : BasePage
    {
        string category;
        string region;
        string province;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            
            initSelect();

            #region 启动流程
            
            if (AksRequest.GetString("action") == "create")
            {
                var applicationNo = GenerateApplicationNo();
                var action = AksRequest.GetString("Actions");
                var autoBusinessKey = AksRequest.GetString("AutoBusinessKey");

                region = AksRequest.GetFormString("ddl_region");
                province = AksRequest.GetFormString("ddl_province");

                if (string.IsNullOrEmpty(action))
                {
                    ErrorMsg("对不起，发起失败，或者暂时不支持该流程手动发起");
                }
                if (action.Equals("DegradeStore"))
                {
                    ErrorMsg("对不起，暂时不支持手动发起门店关闭/降级");
                }

                if (province == "")
                {
                    ErrorMsg("请选择省份！");
                }
                if (region == "")
                {
                    ErrorMsg("请选择区域！");
                }

                TaskAPI["Actions"] = action;
                TaskAPI.InitTask(UserAPI, applicationNo);
                if (action.Equals("ChangeStore")) 
                {
                    category = "Store";
                    TaskAPI.Summary = "提交基本信息变更/基本信息变更";
                }
                else if (action.Equals("ChangeDevice")) 
                {
                    category = "Device";
                    TaskAPI.Summary = "提交设备信息变更/设备信息变更";
                }
                else if (action.Equals("ChangeDealer"))
                {
                    category = "Store";
                    TaskAPI.Summary = "提交经销商更换信息/经销商更换";
                }
                else if (action.Equals("ChangeContract")) 
                {
                    category = "Contract";
                    TaskAPI.Summary = "提交合同信息变更/合同信息变更";
                }
                else if (action.Equals("DegradeStore"))
                {
                    category = "Store";
                    TaskAPI.Summary = "登记门店关闭or降级/门店关闭或降级";
                }
                else if (action.Equals("Transfer"))
                {
                    category = "Device";
                    TaskAPI.Summary = "提交设备三方转移信息/设备三方转移";
                }
                else if (action.Equals("DiscardDevice"))
                {
                    category = "Device";
                    TaskAPI.Summary = "登记设备报废or库存/设备报废或库存";
                }
                else if (action.Equals("BatchStore"))
                {
                    category = "Store";
                    TaskAPI.Summary = "提交基本信息变更/(批量)基本信息变更";
                }
                else if (action.Equals("BatchDevice"))
                {
                    category = "Device";
                    TaskAPI.Summary = "提交设备信息变更/(批量)设备信息变更";
                }
                else if (action.Equals("BatchContract"))
                {
                    category = "Contract";
                    TaskAPI.Summary = "提交合同信息变更/(批量)合同信息变更";
                }
                else if (action.Equals("MDCItss"))
                {
                    category = "Itss";
                    TaskAPI.Summary = "提交MDCItss申请/Itss提交申请";
                }
                TaskAPI["Region"] = region;
                TaskAPI["Province"] = province;
                TaskAPI["Category"] = category;
                //TaskAPI.Summary = action.ConvertToCn();
                if (!string.IsNullOrEmpty(autoBusinessKey))
                {
                    TaskAPI["AutoBusinessKey"] = autoBusinessKey;
                }

                //todo 从界面中取出数据调用下面这个函数，第三个参数分为 Store Device Contract，可以从上面的action里取
                if(action.Equals("MDCItss"))
                {
                    TaskAPI.SetStoreItssRecipient(region, province, category);
                    TaskAPI["R_Start_Apply"] = new object[1] { UserAPI.UserName };
                }else
                {
                    TaskAPI.SetStoreDataChangeRecipient(region, province, category);
                    TaskAPI["R_Submit_Data"] = new object[1] { UserAPI.UserName };
                }
                
                if (TaskAPI.Send())
                {
                    var url = string.Format("pages/smd/SelectChange.aspx?action=redirect&page={0}&process={1}&incident={2}",
                        action, TaskAPI.Process, TaskAPI.Incident);
                    SuccessMsg(url);
                }
                else
                {
                    ErrorMsg("出现异常");
                }
            }

            #endregion

            #region 页面跳转
            else if (AksRequest.GetString("action") == "redirect")
            {
                var page = AksRequest.GetString("page");
                var processName = AksRequest.GetString("process");
                var incidentNo = AksRequest.GetInt("incident", 0);
                
                var task = TaskHelper.GetTask(processName, incidentNo, page=="MDCItss"?"Start Apply":"Submit Data");

                if (task != null)
                {
                    var url = string.Format("{0}.aspx?taskid={1}", page, task.strTaskId);
                    Response.Redirect(url);
                }
                else
                {
                    Response.Redirect("/SystemError.aspx");
                }
            }
            #endregion

            #region 筛选省份和城市
            else if (AksRequest.GetQueryString("action") == "initProvince")
            {
                var type = AksRequest.GetFormString("type");
                var ar = AksRequest.GetFormString("ar");
                var and = string.Empty;
                if (AksRequest.GetFormString("type") == "province")
                {
                    and = " and [level] = 2 ";
                }
                DbHelperSQL.connectionString = PubConstant.GetConnectionString("smdDB");
                DataTable province =
                    DbHelperSQL.Query(
                        "select * from [t_smd_Config] where parentID = (select configid from [t_smd_Config] where value = '" +
                        ar + "' " + and + ") order by seq asc").Tables[0];
                var result = "";
                if (province.Rows.Count > 0)
                {
                    for (int i = 0; i < province.Rows.Count; i++)
                    {
                        var rst = "";
                        rst += province.Rows[i]["Value"] + ",";
                        rst += province.Rows[i]["Name"] + ",";
                        result += rst + "|";
                    }
                }
                SuccessMsg(result);
                return;
            }
                #endregion

            #region 自动发起流程
            
            else
            {
                var autoBusinessKey = AksRequest.GetQueryString("AutoBusinessKey");
                if (string.IsNullOrEmpty(autoBusinessKey)) return;

                AutoBusinessKey.Value = autoBusinessKey;
                l_autoBusinessKey.Text = TaskHelper.GetNameByAutoKey(autoBusinessKey);
                tb_option.Style.Value = "display:none";
                tb_autoBusinessKey.Visible = true;

                if (autoBusinessKey == Constant.PROCESS_CHANGEDEALER)
                {
                    r_ChangeDealer.Checked = true;
                }
                else if (autoBusinessKey == Constant.PROCESS_CHANGELEVEL)
                {
                    r_DegradeStore.Checked = true;
                }
                else if (autoBusinessKey == Constant.PROCESS_TRANSFER)
                {
                    r_Transfer.Checked = true;
                }
                else if (autoBusinessKey == Constant.PROCESS_CHANGESTATUS)
                {
                    r_DiscardDevice.Checked = true;
                }
                else if (autoBusinessKey == Constant.PROCESS_CHANGEOTHER)
                {
                    l_autoBusinessKey.Text = "";
                    tb_option.Style.Value = "display:";
                    tb_autoBusinessKey.Visible = false;
                }
                else if (autoBusinessKey == Constant.PROCESS_MDCITSS)
                {
                    r_MDCItss.Checked = true;
                }
            }

            #endregion
        }

        protected void initSelect() 
        {

            ConfigService configService = new ConfigService();
            #region 门店区域
            DataTable dt_region = configService.GetList("ParentId = (select configid from t_smd_Config where code='M_MDQY') order by seq").Tables[0];
            ddl_region.Items.Add(new ListItem("==请选择==", ""));
            foreach (DataRow row in dt_region.Rows)
            {
                ddl_region.Items.Add(new ListItem(row["Name"].ToString(), row["Name"].ToString()));
            }
            #endregion

            
            #region 门店省份
            ddl_province.Items.Add(new ListItem("==请选择==", ""));
            #endregion
        }

    }
}